package com.qingge.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.Stu;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.service.IStuService;
import com.qingge.springboot.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xyc
 * @since 2022-04-12
 */
@RestController
@RequestMapping("/stu")
public class StuController {

    @Resource
    private IStuService stuService;

    @Resource
    private IUserService userService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Stu stu) {

        // 新增
        if (stu.getId() == null) {

            // 先新增 用户表里学生的账号信息
            Random random = new Random();  // 随机生成学号
            String number = "";
            for (int i = 0; i < 8; i++) {
                number += random.nextInt(10);
            }
            User user = new User();
            user.setUsername(number);  // 设置学号
            user.setPassword("123"); // 默认密码 123
            user.setCreateTime(new Date());
            user.setRole("ROLE_STUDENT");
            if (stu.getName() != null) {
                user.setNickname(stu.getName());
            }
            userService.save(user);
            stu.setUid(user.getId());
        }
        stuService.saveOrUpdate(stu);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(stuService.removeById(id));
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(stuService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(stuService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(stuService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String sex,
                           @RequestParam(defaultValue = "") String college,
                           @RequestParam(defaultValue = "") String grade) {
        return Result.success(stuService.findPage(new Page<>(pageNum, pageSize), name, sex, college, grade));
    }

    @GetMapping("/find")
    public Result find() {
        return Result.success(stuService.list());
    }
}

